<template>
  <ContentWrap>
    <!--    顶部查询项-->
    <el-form :model="form" inline label-width="100px">
      <el-form-item :label="t('discount.code_title')">
        <el-input
          v-model="form.code_title"
          clearable
          :placeholder="'请输入' + t('discount.code_title')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item :label="t('discount.status')">
        <el-select
          v-model="form.status"
          filterable
          :placeholder="'请选择' + t('discount.status')"
          clearable
          style="width: 250px"
        >
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="initialize">查询</el-button>
        <el-button icon="Refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <!--    操作项-->
    <div class="flex flex-items-center my-5">
      <el-button type="primary" @click="handleAdd('add')">
        {{ t('action.add') }}
      </el-button>
    </div>
    <!-- 表格主体 -->
    <el-table
      :data="dataList"
      highlight-current-row
      stripe
      border
      v-loading="tableLoading"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center' }"
    >
      <el-table-column :label="t('productMerge.id')" prop="id" width="100px" />
      <el-table-column :label="t('discount.code_title')" width="400px">
        <template #default="{ row }">
          <p>{{ row.code_title }}</p>
          <p>{{ row.code_title_value }}</p>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('discount.discount_category')"
        prop="discount_category_value"
        width="300px"
      />
      <el-table-column :label="t('discount.status')" width="200px">
        <template #default="{ row }">
          <el-switch
            v-if="row.source == 1"
            v-model="row.status"
            inlinePrompt
            active-text="启用"
            inactive-text="禁用"
            :active-value="1"
            :inactive-value="0"
            @change="handleChangeStatus('single', row)"
          />
          <p v-if="row.source == 2">{{ row.status == 1 ? '启用' : '禁用' }} </p>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('productMerge.creator')"
        prop="creator"
        width="200px"
        :show-overflow-tooltip="true"
      />

      <el-table-column
        :label="t('productMerge.create_time')"
        prop="create_time"
        :width="calculateColumnWidth(dataList, 'create_time')"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('productMerge.updater')"
        prop="updater"
        width="200px"
        :show-overflow-tooltip="true"
      />

      <el-table-column
        :label="t('productMerge.update_time')"
        prop="update_time"
        :width="calculateColumnWidth(dataList, 'update_time')"
        :show-overflow-tooltip="true"
      />
      <el-table-column fixed="right" label="操作" width="200px">
        <template #default="{ row }">
          <el-button @click="handleJump('edit', row)" size="small" v-if="row.source == 1">
            {{ t('order.edit') }}
          </el-button>

          <el-button type="success" @click="handleJump('detail', row)" size="small">
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页-->
    <Pagination
      :total="paginationTotal"
      v-model:page="form.pageIndex"
      v-model:limit="form.pageSize"
      @pagination="initialize"
    />
  </ContentWrap>
</template>

<script setup lang="ts">
import Pagination from '@/components/Pagination/index.vue'
import { ContentWrap } from '@/components/ContentWrap'
import { useEnumeratePicker, calculateColumnWidth } from '@/utils'
import { getListApi, getFieldEnumApi, changeStatusApi } from '@/api/discount'

const { t } = useI18n()
const { push } = useRouter()

const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])
const statusList = ref<any[]>([])
const paginationTotal = ref<number>(0)

const form = ref<Record<string, any>>({
  code_title: '',
  status: '',
  pageIndex: 1,
  pageSize: 30
})
const handleChangeStatus = (type: string, row: Record<string, any>) => {
  ElMessageBox.confirm(
    `是否确认状态流转为${row.status === 1 ? '启用' : '禁用'}？`,
    t('purchase.logistics.tips'),
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        const resp = await changeStatusApi({
          ids: [row.id],
          status: row.status
        })
        if (resp.code === 0) {
          ElMessage.success(t('market.industryNews.statusMsg'))
          await initialize()
        }
      } catch (e) {
        await initialize()
      }
    })
    .catch(() => {
      row.status = row.status === 1 ? 0 : 1
    })
}

//点击跳转到新增
const handleAdd = (type: string) => {
  push(`/oaperations/discount/${type}`)
}

//跳转
const handleJump = (type: string, row: Record<string, any>) => {
  const path = ref<string>('') // 默认值为空字符串
  path.value = `/oaperations/discount/${type}`
  push({ path: path.value, query: { id: row.id } })
}

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getFieldEnumApi({ field: 'all' })
  statusList.value = resp.data.status
}

//初始化请求
const initialize = async () => {
  tableLoading.value = true
  const params = JSON.parse(JSON.stringify(form.value))
  delete params.date
  if (params.order_no && !params.order_type) {
    ElMessage.error('请选择' + t('productMerge.order_type'))
    tableLoading.value = false
    return
  }
  const resp = await getListApi(params)
  dataList.value = resp.data.list

  paginationTotal.value = resp.data.total
  tableLoading.value = false
}

//重置查询项
const reset = () => {
  form.value = {
    code_title: '',
    status: '',
    pageIndex: 1,
    pageSize: 30
  }
  paginationTotal.value = 0
  initialize()
}

onMounted(() => {
  getDropDownBoxInfo()
  initialize()
})
</script>

<style lang="less" scoped></style>
